package com.akk.utils;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class JExcelService {

    public List<Map> readExcel(InputStream file){
        List<Map> list = new ArrayList<>();
        try {
            Workbook workbook = Workbook.getWorkbook(file);
            Sheet sheet[] = workbook.getSheets();
            for (int a = 0;a < sheet.length;a++){
                Sheet sheet1 = sheet[a];
                if (sheet1.getRows() < 2)
                    continue;
                Cell titles[] = sheet1.getRow(0);
                for (int i = 1;i < sheet1.getRows();i++){
                    Cell rows[] = sheet1.getRow(i);
                    Map map = new HashMap();
                    if (StringUtils.isEmpty(rows[0].getContents()) || StringUtils.isEmpty(rows[2].getContents()))
                        continue;
                    for (int index = 0;index<titles.length;index++){
                        String title = titles[index].getContents();
                        if (title.indexOf("_") != -1)
                            title = replaceUnderlineAndfirstToUpper(title,"_","");
                        map.put(title,rows[index].getContents());
                    }
                    list.add(map);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        return list;
    }

    public String replaceUnderlineAndfirstToUpper(String srcStr,String org,String ob)
    {
        String newString = "";
        int first=0;
        while(srcStr.indexOf(org)!=-1)
        {
            first=srcStr.indexOf(org);
            if(first!=srcStr.length())
            {
                newString=newString+srcStr.substring(0,first)+ob;
                srcStr=srcStr.substring(first+org.length(),srcStr.length());
                srcStr=firstCharacterToUpper(srcStr);
            }
        }
        newString=newString+srcStr;
        return newString;
    }

    public String firstCharacterToUpper(String srcStr) {
        return srcStr.substring(0, 1).toUpperCase() + srcStr.substring(1);
    }

}
